import requests
import json
import os
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client['Bilibili']
collection = db['detail']

if not os.path.exists('Bilibili'):
    os.makedirs('Bilibili')

page = 1
count = 1
while True:
    url = f"https://api.bilibili.com/pgc/season/index/result?st=1&order=3&season_version=-1&spoken_language_type=-1&area=-1&is_finish=-1&copyright=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&sort=0&page={page}&season_type=1&pagesize=20&type=1"
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36"
    }
    response = requests.get(url,headers=headers)
    html = response.text
    lists = json.loads(html)["data"]["list"]
    if not lists:
        print('爬取结束...')
        break
    for i in range(0,len(lists)):
        img_url = lists[i]['cover']
        img_res = requests.get(img_url)
        file_path = f"./Bilibili/{count}.jpg"
        with open(file_path, "wb") as f:
            f.write(img_res.content)

        print(f'正在爬取第{page}页的{lists[i]['title']}...')
        document = {
            "名称":lists[i]['title'],
            "追番人数":lists[i]['order'],
            "封面": file_path,
            "评分": lists[i]['score'],
            "字幕": lists[i]['subTitle']
        }
        result = collection.insert_one(document)
        count+=1
    page+=1
client.close()